from docx import Document
from pygtrans import Translate
import shutil


def google_translate_texts(old_data_list, old_language, new_language):
    """
    :param old_data_list: list[]，需要翻译的数据列表
    :param old_language: 需要翻译的源语言,默认是"zh-CN"
    :param new_language: 翻译后的目标语言
    :return: 返回翻译后的目标语言数据列表
    """
    client = Translate(source=old_language, fmt='text', target=new_language)
    new_datas = client.translate(old_data_list)
    new_data_list = []
    for i in new_datas:
        new_data_list.append(i.translatedText)
    return new_data_list


def find_replace_text(doc_path, target_text, replacement_text):
    """
    :param doc: 文件路径
    :param target_text:源文本
    :param replacement_text:目标文本
    :return:
    """
    doc = Document(doc_path)
    for paragraph in doc.paragraphs:
        if target_text in paragraph.text:
            inline = paragraph.runs
            for i in range(len(inline)):
                if target_text in inline[i].text:
                    text = inline[i].text.replace(target_text, replacement_text)
                    inline[i].text = text
    doc.save(doc_path)
    print("替换成功")


def copy_file(source, destination):
    """
    :param source: 源文件路径
    :param destination: 目标文件路径
    :return:
    """
    try:
        shutil.copy(source, destination)
        print("文件拷贝成功")
    except IOError as e:
        print("文件拷贝失败：", e)


file_path = r"/Users/admin/Desktop/静静上学/毕业论文/论文.docx"
new_file_path = r"/Users/admin/Desktop/静静上学/毕业论文/论文副本.docx"
copy_file(file_path, new_file_path)
doc = Document(file_path)
for para in doc.paragraphs:
    # 拿到源数据
    old_data1 = para.text
    print(old_data1)
    # 将源数据进行翻译
    new_data = google_translate_texts(old_data_list=[old_data1], old_language="zh-CN", new_language="en")
    print(new_data[0])
    # 替换到副本中
    if new_data[0] != old_data1:
        find_replace_text(new_file_path, old_data1, new_data[0])
    else:
        print("不进行替换")
    print("--" * 18)

for table in doc.tables:
    for row in table.rows:
        for cell in row.cells:
            # 拿到源数据
            old_data2 = cell.text
            print(old_data2)
            # 将源数据进行翻译
            new_data2 = google_translate_texts(old_data_list=[old_data2], old_language="zh-CN", new_language="en")
            print(new_data2[0])
            # 替换到副本中
            if new_data2[0] != old_data2:
                find_replace_text(new_file_path, old_data2, new_data2[0])
                print("替换成功")
            else:
                print("不进行替换")
            print("--" * 18)
